<?php
namespace app\index\controller;

use app\facade\Auth;
use app\facade\Redis;
use think\Db;
use think\Exception;

class Agent extends Base
{
    public function getInfo(){
        $uid = $this->request->user_id;
        $user =Db::table("tb_card_shop")->where('id', $uid)->find();
        $user["withdrawal_done"] =Db::table("tb_shop_withdrawal_record")->where("uid",$uid)->whereIn("status","0,1")->where("deal_status",0)->sum("money");
        $user["withdrawal_doing"] =Db::table("tb_shop_withdrawal_record")->where("uid",$uid)->where("status",1)->where("deal_status",1)->sum("money");
        return $this->sendSuccess('', ["user"=>$user]);
    }

    public function industry(){
        $data =Db::table("tb_industry")->select();
        return $this->sendSuccess('', ["data"=>$data]);
    }

    public function shopApply(){
        $uid = $this->request->user_id;
        $user= $this->request->user;
        $data = $this->request->post();
        $mobile = $data["mobile"];
        $info = Db::table("tb_shop_apply")->where("uid",$uid)->where("mobile",$mobile)->find();
        if ($info){
            //0 待审核 1 已审核 2 拒绝
            if ($info["status"]==0){
                return $this->sendFail("此手机号的商户正在审核中");
            }
            if ($info["status"]==1){
                return $this->sendFail("此手机号的商户已审核通过");
            }
            if ($info["status"]==2){
                return $this->sendFail("此手机号的商户已审核已被拒绝，请重新编辑提交");
            }
        }
        $validate = new \app\validate\ShopApply;
        if (!$validate->check($data)) {
            return $this->sendFail($validate->getError());
        }
        $data["uid"]=$uid;
        $data["status"]=0;
        $data["time"]=time();
        $data["type"]=$user["type"]+1;
        $data =Db::table("tb_shop_apply")->insertGetId($data);
        return $this->sendSuccess('', ["data"=>$data]);
    }

    public function shopApplyEdit(){
        $uid = $this->request->user_id;
        $data = $this->request->post();
        $id = $data["id"];
        $info = Db::table("tb_shop_apply")->where("uid",$uid)->where("id",$id)->find();
        if (!$info){
            return $this->sendFail("你没有此申请");
        }
        if ($info["status"]==0){
            return $this->sendFail("此手机号的商户正在审核中");
        }
        if ($info["status"]==1){
            return $this->sendFail("此手机号的商户已审核通过");
        }

        $validate = new \app\validate\ShopApply;
        if (!$validate->check($data)) {
            return $this->sendFail($validate->getError());
        }
        $data["uid"]=$uid;
        $data["status"]=0;
        $user =Db::table("tb_shop_apply")->where("id",$id)->update($data);
        return $this->sendSuccess('', ["user"=>$user]);
    }

    public function shopApplyList(){
        $uid = $this->request->user_id;
        $pageSize = $this->request->post("pageSize");
        $page = $this->request->post("page");
        $status = $this->request->post("status");
        if (!$pageSize){
            $pageSize = 10;
        }
        if (!$page){
            $page = 1;
        }
        $sql =Db::table("tb_shop_apply") ->alias('apply')->join('tb_card_shop shop','apply.shop_id = shop.id',"LEFT");
        $sql = $sql->field("apply.*,shop.username,shop.pass")->where("apply.uid",$uid);
        if (!empty($status)){
            $sql = $sql->where("apply.status",$uid);
        }
        $list = $sql  ->order("id asc")->page($page)->paginate($pageSize);
        return $this->sendSuccess('',$list);
    }

    public function shopApplyDetail(){
        $uid = $this->request->user_id;
        $data = $this->request->post();
        $id = $data["id"];
        $data =  Db::table("tb_shop_apply")->where("id",$id)->where("uid",$uid)->find();
        if ($data){
            $license = get_table_field('tb_file','id',$data['license'],'save_name,file_name,type');
            $data["license_url"]=$license;
            $img = get_table_field('tb_file','id',$data['img'],'save_name,file_name,type');
            $data["img_url"]=$img;
        }
        return $this->sendSuccess('',$data);
    }

    public function shopStatistics(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $type = $user["type"];
        $col = "agent_id";
        if ($type==2){
            $col = "shop_id";
        }
        $today = strtotime(date('Y-m-d',time())." 00:00:00");
        $yestoday = $today-24*3600;
        $tomorow = $today+24*3600;

        $data=[];
        $data["all"] =  Db::table("tb_card_info")->where($col,$uid)->count("id");
        $data["use"] =  Db::table("tb_card_info")->where($col,$uid)->where("status",1)->count("id");
        $data["unuse"] =   $data["all"] - $data["use"];
        $data["yestoday_use"] =  Db::table("tb_card_info")->where($col,$uid)->where("status",1)
            ->where("use_time",">=",$yestoday) ->where("use_time","<",$today)->count("id");
        $data["today_use"] =  Db::table("tb_card_info")->where($col,$uid)->where("status",1)
            ->where("use_time",">=",$today) ->where("use_time","<",$tomorow)->count("id");
        $data["child"] = 0;
        $data["parent"] = null;
        if ($type==1){
            $data["child"] =  Db::table("tb_card_shop")->where("parent",$uid)->count("id");
        }else{
            $data["parent"]=  Db::table("tb_card_shop")->where("id",$user["parent"])->count("id");
        }
        return $this->sendSuccess('',$data);
    }

    public function childs(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $type= $user["type"];
        $pageSize = $this->request->post("pageSize");
        $page = $this->request->post("page");
        $word = $this->request->post("word");
        $last_id = $this->request->post("last_id");


        $sql = Db::table("tb_card_shop");
        if (!empty($word)){
            $sql= $sql ->where("username","like","%".$word."%");
        }
        $que_uid = $uid;
        if (!empty($last_id)){
            $que_uid =$last_id;
            $col = "shop_id";
        }else{
            if ($type==1){
                $col = "agent2_id";
            }elseif ($type==2){
                $col = "shop_id";
            }else{
                return $this->sendFail("您没有下级");
            }
        }
        $sql= $sql ->where("parent",$que_uid);
        $pagelist =$sql ->order("id asc")->page($page)->paginate($pageSize);
        $list = $pagelist->all();


        $today = strtotime(date('Y-m-d',time())." 00:00:00");
        $yestoday = $today-24*3600;
        $tomorow = $today+24*3600;
        foreach ($list as $k => $v){
            $list[$k]['all'] = Db::table("tb_card_info")->where($col,$v["id"])->count("id");
            $list[$k]['use'] = Db::table("tb_card_info")->where($col,$v["id"])->where("status",1)->count("id");
            if ($col == "agent2_id"){
                $list[$k]["dispatched"]=Db::table("tb_card_info")->where($col,$v["id"])->where('shop_time > 0')->count("id");
            }
            $list[$k]["today_use"] =  Db::table("tb_card_info")->where($col,$v["id"])->where("status",1)
                ->where("use_time",">=",$today) ->where("use_time","<",$tomorow)->count("id");
            $pagelist[$k]=$list[$k];
        }
        return $this->sendSuccess('',$pagelist);
    }

    public function distributionCardByCardNo(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $type = $user["type"];
        if ($type!=1&&$type!=2){
            return $this->sendFail("代理商才能分配卡");
        }
        $shop = $this->request->post("shop");
        $obj = Db::table("tb_card_shop")->where("type",($type+1))->where('id', $shop)->where('parent', $uid)->find();
        if (!$obj){
            return $this->sendFail("商户不存在");
        }
        if ($obj["bonus"]==0){
            return $this->sendFail("此商户未配置分红比例，请联系管理员");
        }
        $start = $this->request->post("start");
        $end = $this->request->post("end");
        if ($start<1000000000){
            return $this->sendFail("开始卡号错误");
        }
        if ($start>9999999999){
            return $this->sendFail("开始卡号错误");
        }
        if ($end<1000000000){
            return $this->sendFail("结束卡号错误");
        }
        if ($end>9999999999){
            return $this->sendFail("结束卡号错误");
        }
        $res = 0;
        if ($type==1){
            $sqldata=[];
            $sqldata["agent2_time"]=time();
            $sqldata["agent2_id"]=$shop;
            $res = Db::table("tb_card_info")->where("card",">=",$start)->where("card","<=",$end)
                ->where("status",0)->where("agent_id",$uid)->where("agent2_id is null")->update($sqldata);

        }else{
            $sqldata=[];
            $sqldata["shop_time"]=time();
            $sqldata["shop_id"]=$shop;
            $res = Db::table("tb_card_info")->where("card",">=",$start)->where("card","<=",$end)
                ->where("status",0)->where("agent2_id",$uid)->where("shop_id is null")->update($sqldata);

        }
        if ($res) {
            return $this->sendSuccess("您分配了".$res."张卡");
        } else {
            return $this->sendFail("操作失败".Db::table("tb_card_info")->getLastSql());
        }
    }

    public function distributionCardByNum(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $type = $user["type"];
        if ($type!=1&&$type!=2){
            return $this->sendFail("代理商才能分配卡");
        }
        $shop = $this->request->post("shop");
        $obj = Db::table("tb_card_shop")->where("type",($type+1))->where('id', $shop)->where('parent', $uid)->find();
        if (!$obj){
            return $this->sendFail("商户不存在");
        }
        if ($obj["bonus"]==0){
            return $this->sendFail("此商户未配置分红比例，请联系管理员");
        }
        $start = $this->request->post("start");
        $num =intval( $this->request->post("num"));
        if ($num<=0){
            return $this->sendFail("数量错误");
        }
        if ($start<1000000000){
            return $this->sendFail("开始卡号错误");
        }
        if ($start>9999999999){
            return $this->sendFail("开始卡号错误");
        }
        if ($type==1){
            $sqldata=[];
            $sqldata["agent2_time"]=time();
            $sqldata["agent2_id"]=$shop;
            $list= Db::table("tb_card_info")->where("card",">=",$start)
                ->where("status",0)->where("agent_id",$uid)->where("agent2_id is null")->limit(0,$num)->select();
            foreach ($list as $index=>$value){
                Db::table("tb_card_info")->where("id",$value["id"]) ->update($sqldata);
            }
        }else{
            $sqldata=[];
            $sqldata["shop_time"]=time();
            $sqldata["shop_id"]=$shop;
            $list = Db::table("tb_card_info")->where("card",">=",$start)
                ->where("status",0)->where("agent2_id",$uid)->where("shop_id is null")->limit(0,$num)->select();
            foreach ($list as $index=>$value){
                Db::table("tb_card_info")->where("id",$value["id"]) ->update($sqldata);
            }
        }
        return $this->sendSuccess("您分配了".sizeof($list)."张卡");
    }

    public function mycards(){
        $uid = $this->request->user_id;
        $pageSize = $this->request->post("pageSize");
        $page = $this->request->post("page");
        $word = $this->request->post("word");
        $status = $this->request->post("status");
        $user = $this->request->user;
        $type = $user["type"];
        $col = "info.agent_id";
        if ($type==2){
            $col = "info.agent2_id";
        }elseif ($type==3){
            $col = "info.shop_id";
        }

        $sql = Db::table("tb_card_info")->field("info.*,agent.nickname as agent,agent2.nickname as agent2,shop.nickname as shop")
            ->alias("info")->where($col,$uid)->order('status asc,id asc');
        if (!empty($word)){
           $sql ->where("info.card","like","%".$word."%");
        }
        if (!empty($status)){
            $sql ->where("info.status",$status);
        }
        $sql->join('tb_card_shop agent',"info.agent_id=agent.id","left");
        $sql->join('tb_card_shop agent2',"info.agent2_id=agent2.id","left");
        $sql->join('tb_card_shop shop',"info.shop_id=shop.id","left");
        $list = $sql->page($page)->paginate($pageSize);
        return $this->sendSuccess("",$list);
    }


    public function withdrawal(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $alipay=$this->request->param("alipay");
        $alipay_name=$this->request->param("alipay_name");
        //提现金额
        $money = round(floatval($this->request->param("money")),2);
        //最小提现金额
        $withdrawal_min = Redis::hget("system","withdrawal_min");
        //提现手续费
        $withdrawal_fee = round(floatval(Redis::hget("system","withdrawal_fee")),4);

        if ( $money<$withdrawal_min){
            return $this->sendFail("最小提现金额为：".$withdrawal_min);
        }
        $userMoney =$user["money"]-$money;
       if ($userMoney<0) {
           return $this->sendFail("用户余额不足");
       }
        $withdrawal_fee_money = $money*$withdrawal_fee;
       Db::startTrans();
       try{
           //1 减少用户余额
           $data=[];
           $data["money"]=$userMoney;
           $res = Db::table("tb_card_shop")->where("id",$uid)->update($data);
           if (!$res){
               Db::rollback();
               return $this->sendFail("扣除账户资金失败");
           }
           //2 新增提现记录
           $withdrawal =Db::table("tb_shop_withdrawal_record")->insert([
               "uid"=>$uid,
               "money"=>$money,
               "status"=>0,
               "alipay"=>$alipay,
               "alipay_name"=>$alipay_name,
               "apply_time"=>time(),
               "fee"=>$withdrawal_fee,
               "fee_money"=>$withdrawal_fee_money,
           ]);
           if (!$withdrawal){
               Db::rollback();
               return $this->sendFail("提现申请失败");
           }
           Db::commit();
           return $this->sendSuccess("操作成功");
       }catch (Exception $e){
           Db::rollback();
           return $this->sendFail("提现异常：".$e->getMessage());
       }
    }

    public function withdrawalRecord(){
        $uid = $this->request->user_id;
        $pageSize = $this->request->post("pageSize");
        $page = $this->request->post("page");
        $status = intval($this->request->post("status"));
        $deal_status = intval($this->request->post("deal_status"));
        $obj= Db::table("tb_shop_withdrawal_record")->order("status asc");
        if (isset($status)&&$status>0){
            $obj->where("status",$status);
        }
        if (isset($deal_status)&&$deal_status>0){
            $obj->where("deal_status",$deal_status);
        }
        $list = $obj->where("uid",$uid)->page($page)->paginate($pageSize);
        return $this->sendSuccess("",$list);
    }

    public function bounsRecord(){
        $uid = $this->request->user_id;
        $pageSize = $this->request->post("pageSize");
        $page = $this->request->post("page");
        $obj= Db::table("tb_shop_bouns_record")->order("time desc");
        $list = $obj->where("shop_id",$uid)->page($page)->paginate($pageSize);
        return $this->sendSuccess("",$list);
    }

    public function bounsTotal(){
        $uid = $this->request->user_id;
        $obj= Db::table("tb_shop_bouns_record")->order("time desc");
        $money= $obj->where("shop_id",$uid)->sum("money");
        return $this->sendSuccess("",$money);
    }


    public function teamInfo(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $type=$user["type"];

        $last =Db::table("tb_card_shop")->where('id', $user["parent"])->find();
        $data=[];
        $data["last"]=$last;
        $data["card_sum"]=0;
        $data["child"]=0;
        $data["card_used"]=0;
        $data["card_dispatched"]=0;
        if ($type==1){
            $data["card_sum"]=Db::table("tb_card_info")->where('agent_id', $uid)->count("id");
            $data["card_used"]=Db::table("tb_card_info")->where('agent_id', $uid)->where('status', 1)->count("id");
            $data["card_dispatched"]=Db::table("tb_card_info")->where('agent_id', $uid)->where('agent2_time > 0')->count("id");
            $data["child"]=Db::table("tb_card_shop")->where('parent',$uid)->count("id");
        }else if ($type==2){
            $data["card_sum"]=Db::table("tb_card_info")->where('agent2_id', $uid)->count("id");
            $data["card_used"]=Db::table("tb_card_info")->where('agent2_id', $uid)->where('status', 1)->count("id");
            $data["card_dispatched"]=Db::table("tb_card_info")->where('agent2_id', $uid)->where('shop_time > 0')->count("id");
            $data["child"]=Db::table("tb_card_shop")->where('parent',$uid)->count("id");
        }else if ($type==3){
            $data["card_sum"]=Db::table("tb_card_info")->where('shop_id', $uid)->count("id");
            $data["card_used"]=Db::table("tb_card_info")->where('shop_id', $uid)->where('status', 1)->count("id");
            $data["card_dispatched"]=0;
            $data["child"]=0;
        }

        return $this->sendSuccess("",$data);
    }

    public function editPass(){
        $uid = $this->request->user_id;
        $user = $this->request->user;
        $old_pass = $this->request->post("old_pass");
        $new_pass = $this->request->post("new_pass");
        if (empty($old_pass)||empty($new_pass)){
            return $this->sendFail("参数错误");
        }

        if (strlen($new_pass)<6||strlen($new_pass)>12){
            return $this->sendFail("请输入6-12位新密码");
        }

        if ($old_pass == $new_pass){
            return $this->sendFail("新旧密码一致，没有发生变化");
        }

        if (md5($old_pass)!=$user["pass"]){
            return $this->sendFail("您输入的旧密码错误");
        }
        $res=Db::table("tb_card_shop")->where('id', $uid)->update(["pass"=>md5($new_pass)]);
        if ($res){
            return $this->sendSuccess("修改成功");
        }
        return $this->sendFail("修改失败");
    }

}
